package com.atguigu.spzx.feign.cart.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

/**
 * ClassName: AddTokenRequestInterceptor
 * Package: com.atguigu.spzx.feign.cart.interceptor
 * Description:
 *      openFeign的请求拦截器 -> 在发送请求前进行拦截增强 -> 实现RequestInterceptor接口并且加入ioc即可
 * @Author 刘强
 * @Create 2024/7/17 17:58
 * @Version 1.0
 */
public class AddTokenRequestInterceptor implements RequestInterceptor {
    /**
     * 跟feignClient设置请求头，携带token
     * @param requestTemplate  feignClient
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取原来的请求报文  --> 请求上下文中
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("token");
        requestTemplate.header("token",token);
    }
}
